#include <iostream>
#include <string>
#include <unistd.h>
#include <cstring>
#include "Log.hpp"
#include <netinet/in.h>
#include <sys/types.h>
#include <strings.h>
#include <arpa/inet.h>

#include <sys/socket.h>
enum
{
    SOCK_ERR = 1,
    BIND_ERR
};
void Usage(std::string str)
{
    printf("Usage:\n     %s local_ip local_port\n", str.c_str());
}
LogType log;
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
    }
    std::string ip_addr = argv[1];
    uint16_t port = std::stoi(argv[2]);
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        log(FATAL, __LINE__, __FILE__, "socket create error!\n");
        exit(SOCK_ERR);
    }
    struct sockaddr_in local;
    bzero(reinterpret_cast<void *>(&local), sizeof(local));
    local.sin_family = AF_INET;
    local.sin_port = htons(port);
    local.sin_addr.s_addr = inet_addr(ip_addr.c_str());
    bind(sockfd, reinterpret_cast<sockaddr *>(&local), sizeof(local));
    std::string message;
    while (true)
    {
        std::cout << "Please Enter##";
        std::getline(std::cin, message);
        ssize_t n = sendto(sockfd, message.c_str(), strlen(message.c_str()), 0, reinterpret_cast<const sockaddr *>(&local), sizeof(local));
        if (n < 0)
        {
            log(ERROR, __LINE__, __FILE__, "sendto error!");
            break;
        }

        // 接收服务端
        struct sockaddr_in peer;
        bzero(&peer, sizeof(peer));
        char buffer[1024];
        uint32_t peer_len = -1;
        n = recvfrom(sockfd, static_cast<void *>(buffer), sizeof(buffer), 0, reinterpret_cast<sockaddr *>(&peer), &peer_len);
        std::cout << "server response##" <<buffer << std::endl;
    }
    return 0;
}